package com.tools.cleanmaster.controller;

import android.content.Context;
import android.os.Build;

import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.TrashesData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lianzhan on 15/12/23.
 */
public class TrashDeepHandler extends TrashHandler {
    private List<ITrashScanListener> mScanListeners = new ArrayList<ITrashScanListener>();
    private Context mContext;
    private List<TrashScanner> mDeepScanners = new ArrayList<TrashScanner>();
    private int mTrashTypesCount;
    private TrashesData mTrashesData;

    public TrashDeepHandler(Context context, TrashType[] types) {
        super(context, types);
        this.mContext = context;
    }

    @Override
    protected int getTrashTypesCount() {
        return mTrashTypesCount;
    }

    @Override
    public void scan(ITrashScanListener listener) {
        mStopRequested = false;
        if (mScanListeners.contains(listener)) {
            return;
        }
        mScanListeners.add(listener);
        doRealScan();
    }

    @Override
    public TrashesData getTrashesData() {
        if (mTrashesData == null) {
            mTrashesData = new TrashesData();
        }
        return mTrashesData;
    }

    @Override
    protected List<ITrashScanListener> getScanListeners() {
        return mScanListeners;
    }

    private void doRealScan() {
        prepareScanners();
        ThreadPool.runOnPool(new Runnable() {
            @Override
            public void run() {
                for (TrashScanner trashScanner : mDeepScanners) {
                    trashScanner.scan(0);
                }
            }
        });
    }

    private void prepareScanners() {

        for (TrashType type : mTrashType) {
            if (type == TrashType.IMAGE_FILE) {
                ImageScanner imageScanner = new ImageScanner(mContext, this);
                mDeepScanners.add(imageScanner);
            } else if (type == TrashType.VIDEO_FILE) {
                VideoScanner videoScanner = new VideoScanner(mContext, this);
                mDeepScanners.add(videoScanner);
            } else if (type == TrashType.LARGE_FILE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                LargeFileScanner fileScanner = new LargeFileScanner(mContext, this);
                mDeepScanners.add(fileScanner);
            }
        }
        mTrashTypesCount = mDeepScanners.size();
    }
}
